import Vue from 'vue'
import VueRouter from 'vue-router'
import Categories from '@/components/categories/Categories.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/index',
      name: 'index',
      component: () => import('@/views/index/Index.vue'),
      children: [
        {
          path: '',
          redirect: 'users'
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('@/components/Users_index.vue')
        },
        {
          path: 'roles',
          name: 'roles',
          component: () => import('@/components/roles/Roles.vue')
        },
        {
          path: 'goods',
          name: 'goods',
          component: () => import('@/components/goods/Goods.vue')
        },
        {
          path: 'rights',
          name: 'rights',
          component: () => import('@/components/roles/rights/Rights')
        },
        {
          path: 'orders',
          name: 'orders',
          component: () => import('@/components/order/Oder.vue')
        },
        {
          path: 'params',
          name: 'params',
          component: () => import('@/components/goods/params/Params.vue')
        },
        {
          path: 'reports',
          name: 'reports',
          component: () => import('@/components/datatab/dataTab')
        },
        {
          path: 'categories',
          name: 'categories',
          component: Categories
        }
      ]
    },
    {
      path: '/',
      redirect: '/index'
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()

  if (!localStorage.user) return next('/login')

  const { token } = JSON.parse(localStorage.user)
  if (token) return next()
  next('/login')
})
export default router
